package com.blog.admin.controller;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.baidu.ueditor.um.Uploader;
import com.blog.admin.bean.User;
import com.blog.admin.service.MenuService;
import com.blog.admin.service.RoleService;
import com.blog.admin.service.UserService;
import com.blog.base.controller.BaseController;
import com.blog.base.service.RedeployMapperService;
import com.blog.util.MD5Util;



/**
 * @todo SystemController
 * @author fg
 * @date 2016年1月19日
 */

@Scope("prototype")
@Controller
@RequestMapping(value="system")
public class SystemController extends BaseController
{ 
	@Resource
	UserService userService;
	
	@Resource
	RoleService roleService;
	
	@Resource
	MenuService menuService;
	
	@Resource
	RedeployMapperService redeployMapperService;
	/**
	 * @todo 跳转登陆页面
	 * @author fg
	 * @date 2016年1月19日
	 */
	@RequestMapping(value="loginPage")
	public ModelAndView login() 
	{
		mav.setViewName("login");
		return mav;
	}
	
	/**
	 * @todo 跳转至欢迎页面
	 * @author fg
	 * @date 2016年1月21日
	 */
	@RequestMapping(value="wellcome")
	public ModelAndView wellcome() 
	{
		mav.setViewName("system/wellcome");
		return mav;
	}
	
	/**
	 * @todo 登陆
	 * @author fg
	 * @date 2016年1月19日
	 */ 
	@RequestMapping(value="/login")
	public String login(User user,HttpServletRequest request,HttpServletResponse response,RedirectAttributes redirectAttributes) 
	{
		if(user==null||StringUtils.isEmpty(user.getUserName())||StringUtils.isEmpty(user.getPassword()))
		{
            request.setAttribute("msg","请输入用户名和密码！");
            return "login"; 
		}
		user.setPassword(MD5Util.MD5(user.getPassword()));
		try
		{
			SecurityUtils.getSubject().login(new UsernamePasswordToken(user.getUserName(), user.getPassword().toCharArray()));
			user.setRoleList(roleService.queryRoleByUserId(user.getId()));
			user.setMenuList(menuService.queryMenuByRoleList(user.getRoleList()));
			return "redirect:index.htm";    
		} 
		catch (AuthenticationException e)
		{
			e.printStackTrace();
            request.setAttribute("msg","用户名或密码错误！");
            return "login"; 
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return "login"; 
		}
	}

	/**
	 * @todo 登陆成功后的主页面
	 * @author fg
	 * @date 2016年3月14日
	 */
	
	@RequestMapping(value="/index")
	public ModelAndView initIndexPage() 
	{
		if(getCurUser()==null)
		{
			mav.setViewName("login");
		}
		else
		{
			mav.setViewName("system/index");
		}
		return mav;
	}
	
	/**
	 * @todo 公共的后台管理进入页面controller
	 * @author fg
	 * @date 2016年3月24日
	 */
	@RequiresRoles(value = { "superAdmin", "developer"},logical=Logical.OR)
	@RequestMapping(value="/admin/{pageName}", method = {RequestMethod.PUT, RequestMethod.POST})
	public ModelAndView commonTurnPage(@PathVariable String pageName) 
	{
		mav.setViewName("admin/"+pageName+"/"+pageName+"_index");
		return mav;
	}
	
	/**
	 * @todo 热部署
	 * @author fg
	 * @date 2016年4月11日
	 */
	@RequiresRoles("developer")
	@RequestMapping(value="/redeploy")
	@ResponseBody
	public JSONObject redeploy() 
	{
		json.put("msg", redeployMapperService.refreshMapper());
		return json;
	}
	
	/**
	 * @todo 退出登录
	 * @author fg
	 * @date 2016年4月12日
	 */
	@RequestMapping(value="/logout")
	public ModelAndView logout() {
		Subject subject = SecurityUtils.getSubject();
		if (subject.isAuthenticated()) {
			subject.logout(); // session 会销毁，在SessionListener监听session销毁，清理权限缓存
		}
		mav.setViewName("login");
		return mav;
	}
	
	/**
	 * @todo 获取图片
	 * @author fg
	 * @throws IOException 
	 * @date 2016年4月16日
	 */
	@RequestMapping("/showImage")
    public void showImage(HttpServletRequest re,HttpServletResponse response,String pic_addr) throws IOException{//pic_addr:图片路径(d:\\upload\a.jpg)
        response.setContentType("image/*");
        FileInputStream fis = null; 
        OutputStream os = null; 
        System.out.println(pic_addr);
        try
		{
        	fis = new FileInputStream(pic_addr);
		} catch (Exception e)
		{
			fis = new FileInputStream(Uploader.IMG_FLODER+"/"+"defult_picture.jpg");
			//e.printStackTrace();
		}
    
    	os = response.getOutputStream();
        try {

            int count = 0;
            byte[] buffer = new byte[1024*8];
            while ( (count = fis.read(buffer)) != -1 )
            {
            	os.write(buffer, 0, count);
            	os.flush();
            }
        }
        catch(Exception e)
        {
        	e.printStackTrace();
        }
        finally 
    	{
        	try {
        		fis.close();
        		os.close();
			} 
        	catch (IOException e) 
        	{
				e.printStackTrace();
			}
        }
    }
	
	
	

	
}
